/**
 * 
 */
package org.hotpotmaterial.codegenn2.service.impl;

import java.util.Date;
import java.util.List;

import org.hotpotmaterial.codegenn2.common.HmCodeGenConstants;
import org.hotpotmaterial.codegenn2.common.enums.PersistEnum;
import org.hotpotmaterial.codegenn2.dao.HmteamAccountProjectMapper;
import org.hotpotmaterial.codegenn2.dao.ProjectMapper;
import org.hotpotmaterial.codegenn2.dto.entity.PageDTO;
import org.hotpotmaterial.codegenn2.dto.request.PageRequestDTO;
import org.hotpotmaterial.codegenn2.entity.HmteamAccount;
import org.hotpotmaterial.codegenn2.entity.HmteamAccountProject;
import org.hotpotmaterial.codegenn2.entity.HmteamAccountProjectExample;
import org.hotpotmaterial.codegenn2.entity.Project;
import org.hotpotmaterial.codegenn2.entity.ProjectExample;
import org.hotpotmaterial.codegenn2.exception.CodeCommonException;
import org.hotpotmaterial.codegenn2.service.IProjectService;
import org.hotpotmaterial.codegenn2.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * @author cakydeveloper
 *
 */
@Service
public class ProjectServiceImpl implements IProjectService {

	@Autowired
	private ProjectMapper projectMapper;

	@Autowired
	private HmteamAccountProjectMapper accountProjectMapper;

	@Override
	public PageDTO<Project> findProjectsByUser(PageRequestDTO searchDTO) {
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		final boolean nameIsNotNull = null != searchDTO.getSearchParams()
				&& null != searchDTO.getSearchParams().get("name");
		// 分页查询
		Page<Project> page = PageHelper.startPage(searchDTO.getPageNum(), searchDTO.getPageSize())
				.doSelectPage(() -> projectMapper.selectByNameAndUserId(
						nameIsNotNull ? (String) searchDTO.getSearchParams().get("name") : null, loginUser.getId()));
		// 构建返回参数
		return PageDTO.<Project>builder().pageNum(page.getPageNum()).pageSize(page.getPageSize()).total(page.getTotal())
				.data(page.getResult()).build();
	}

	@Override
	public PageDTO<Project> findProjects(PageRequestDTO searchDTO) {
		ProjectExample example = new ProjectExample();
		example.createCriteria().andIsDeletedEqualTo(HmCodeGenConstants.DATA_IS_VALID);
		if (null != searchDTO.getSearchParams() && null != searchDTO.getSearchParams().get("name")) {
			example.getOredCriteria().get(0).andNameLike("%" + (String) searchDTO.getSearchParams().get("name") + "%");
		}
		// 分页查询
		Page<Project> page = PageHelper.startPage(searchDTO.getPageNum(), searchDTO.getPageSize())
				.doSelectPage(() -> projectMapper.selectByExample(example));
		// 构建返回参数
		return PageDTO.<Project>builder().pageNum(page.getPageNum()).pageSize(page.getPageSize()).total(page.getTotal())
				.data(page.getResult()).build();
	}

	@Override
	@Transactional
	public int insertProject(Project record) {
		// 默认字段
		setDefaultColumns(record, PersistEnum.insert);
		projectMapper.insertSelective(record);
		// 新增关联关系
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		this.assignProjectPermission(record.getId(), loginUser.getId());
		return 0;
	}

	@Override
	public Project findById(Long id) {
		return projectMapper.selectByPrimaryKey(id);
	}

	@Override
	@Transactional
	public int updateProject(Long id, Project record) {
		// 默认字段
		record.setId(id);
		setDefaultColumns(record, PersistEnum.update);
		return projectMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	@Transactional
	public int delProject(Long id) {
		Project record = projectMapper.selectByPrimaryKey(id);
		if (record != null) {
			setDefaultColumns(record, PersistEnum.delete);
			return projectMapper.updateByPrimaryKeySelective(record);
		}
		return 0;
	}
	
	@Override
	public List<HmteamAccountProject> findProjectAccounts(Long id, String userName) {
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		return accountProjectMapper.selectByUserName(loginUser.getId(), id, userName);
	}

	@Override
	@Transactional
	public int assignProjectPermission(Long id, Long accountId) {
		Date now = new Date();
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		// 查询当前用户与项目关系
		HmteamAccountProjectExample example = new HmteamAccountProjectExample();
		example.createCriteria().andIsDeletedEqualTo(HmCodeGenConstants.DATA_IS_VALID)
				.andHmteamAccountIdEqualTo(loginUser.getId()).andProjectIdEqualTo(id)
				.andIsOwnerEqualTo(0);
		List<HmteamAccountProject> projectAccounts = accountProjectMapper.selectByExample(example);
		if (projectAccounts != null && !projectAccounts.isEmpty()) {
			HmteamAccountProject record = new HmteamAccountProject();
			record.setHmteamAccountId(accountId);
			record.setIsOwner(1);
			record.setProjectId(id);
			record.setCreatedAt(now);
			record.setCreatedBy(loginUser.getUserName());
			record.setLastUpdatedBy(loginUser.getUserName());
			record.setLastUpdatedAt(now);
			record.setLastUpdatedTraceid(loginUser.getTraceId());
			record.setIsDeleted(HmCodeGenConstants.DATA_IS_VALID);
			accountProjectMapper.insertSelective(record);
		} else {
			// 无权限
			throw new CodeCommonException("No permission");
		}
		return 0;
	}
	
	@Override
	@Transactional
	public int delProjectPermission(Long id, Long projectAccountId) {
		Date now = new Date();
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		// 查询当前用户与项目关系
		HmteamAccountProjectExample example = new HmteamAccountProjectExample();
		example.createCriteria().andIsDeletedEqualTo(HmCodeGenConstants.DATA_IS_VALID)
				.andHmteamAccountIdEqualTo(loginUser.getId()).andProjectIdEqualTo(id)
				.andIsOwnerEqualTo(0);
		List<HmteamAccountProject> projectAccounts = accountProjectMapper.selectByExample(example);
		if (projectAccounts != null && !projectAccounts.isEmpty()) {
			HmteamAccountProject record = new HmteamAccountProject();
			record.setId(projectAccountId);
			record.setLastUpdatedBy(loginUser.getUserName());
			record.setLastUpdatedAt(now);
			record.setLastUpdatedTraceid(loginUser.getTraceId());
			record.setIsDeleted(HmCodeGenConstants.DATA_IS_INVALID);
			accountProjectMapper.updateByPrimaryKeySelective(record);
		} else {
			// 无权限
			throw new CodeCommonException("No permission");
		}
		return 0;
	}

	/**
	 * 设置默认字段
	 * 
	 * @param record
	 * @param persisttype
	 */
	private void setDefaultColumns(Project record, PersistEnum persisttype) {
		Date now = new Date();
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		switch (persisttype) {
		case insert:
			record.setCreatedAt(now);
			record.setCreatedBy(loginUser.getUserName());
			record.setLastUpdatedBy(loginUser.getUserName());
			record.setLastUpdatedAt(now);
			record.setLastUpdatedTraceid(loginUser.getTraceId());
			record.setIsDeleted(HmCodeGenConstants.DATA_IS_VALID);
		case update:
			record.setLastUpdatedBy(loginUser.getUserName());
			record.setLastUpdatedAt(now);
			record.setLastUpdatedTraceid(loginUser.getTraceId());
		case delete:
			record.setLastUpdatedBy(loginUser.getUserName());
			record.setLastUpdatedAt(now);
			record.setLastUpdatedTraceid(loginUser.getTraceId());
			record.setIsDeleted(HmCodeGenConstants.DATA_IS_INVALID);
		}
	}

}
